package com.deli.config;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @Description:
 * @Author: xudeli
 * @CreateDate: 2019/9/19 21:23
 **/
@Component
public class MoniterFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(MoniterFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        //全路径
        StringBuffer url = httpServletRequest.getRequestURL();
        String queryString = getQueryString(httpServletRequest);
        chain.doFilter(httpServletRequest, httpServletResponse);
        long end = System.currentTimeMillis() - start;
        logger.info("url=[{}],params=[{}],cost time = [{}]", url, queryString, end);

    }

    private String getQueryString(HttpServletRequest httpServletRequest) {
        //获取到所有的参数
        Enumeration<String> parameterNames = httpServletRequest.getParameterNames();
        StringBuilder stringBuilder = new StringBuilder("");

        while (parameterNames.hasMoreElements()) {
            String nextElement = parameterNames.nextElement();
            String parameter = httpServletRequest.getParameter(nextElement);
            stringBuilder.append(nextElement).append("=").append(parameter).append("&");
        }
        stringBuilder.substring(0, stringBuilder.length() - 1);
        return stringBuilder.toString();
    }

    @Override
    public void destroy() {

    }
}
